package thread.threaddemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadLock4 {
    public static void main(String[] args) throws InterruptedException {
        Lock lock = new ReentrantLock();
       // System.out.println("执行 lock 操作");

        Thread t1 = new Thread(() -> {
            lock.lock();
            System.out.println("线程1得到了锁");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("线程1释放锁");
                lock.unlock();
            }
        });
        t1.start();



        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.lock();
            try {
                System.out.println("线程2获取到了锁");
            } finally {
                lock.unlock();
            }
        });
        t2.start();
        Thread.sleep(1500);

        System.out.println("线程2：" + t2.getState());

//
//        Thread t1 = new Thread(() -> {
//            synchronized (ThreadLock4.class) {
//                System.out.println("线程1得到了锁");
//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println("线程2释放锁");
//            }
//        });
//        t1.start();
//
//        Thread t2 = new Thread(() -> {
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            synchronized (ThreadLock4.class) {
//                System.out.println("线程2获取到了锁");
//            }
//        });
//        t2.start();
//
//        Thread.sleep(1000);
//        System.out.println("线程2：" + t2.getState());

//        synchronized (lock) { // 死等
//
//        }
//
//
//        for (int i = 0; i < 15; i++) {
//            boolean result = lock.tryLock(1 + i, TimeUnit.SECONDS);
//        }
//
////        boolean result = lock.tryLock();
//        boolean result = lock.tryLock(5, TimeUnit.SECONDS);
//        if (result) {
//            // 获取锁成功，执行相应的业务
//        } else {
//            // 获取锁失败，执行相应的业务
//        }
//        try {
//            System.out.println("进入了 try 方法");
//            int i = 10 / 0; // 某一种极端的操作
//        } finally {
//            System.out.println("执行 unlock 操作");
//            lock.unlock();
//        }
    }
}